package db

import (
	"database/sql"
	"fmt"
	"strings"

	_ "github.com/go-sql-driver/mysql"
)

// Client 数据库客户端（封装sql.DB）
type Client struct {
	*sql.DB
}

var DB *Client

func NewClient(addr, user, password string) (*Client, error) {
	dbName := "storage_usg"

	var dbHost, dbPort string
	hostPort := addr
	if hostPort == "" {
		dbHost = "10.125.18.200"
		dbPort = "33306"
	} else {
		parts := strings.Split(hostPort, ":")
		dbHost = parts[0]
		if len(parts) > 1 {
			dbPort = parts[1]
		} else {
			dbPort = "33306"
		}
	}
	if user == "" {
		user = "root"
	}
	if password == "" {
		password = "Unicom@fcp123"
	}

	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true",
		user, password, dbHost, dbPort, dbName)

	db, err := sql.Open("mysql", dataSourceName)
	if err != nil {
		return nil, fmt.Errorf("连接数据库失败：%v", err)
	}

	if err := db.Ping(); err != nil {
		return nil, fmt.Errorf("数据库ping失败：%v", err)
	}

	return &Client{db}, nil
}

// GetUserByUsername 根据用户名查询用户
func (c *Client) GetUserByUsername(username string) (*User, error) {
	query := "SELECT id, username, password FROM user WHERE username = ?"
	row := c.QueryRow(query, username)

	var user User
	err := row.Scan(&user.ID, &user.Username, &user.Password)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, nil // 用户名不存在
		}
		return nil, fmt.Errorf("查询用户失败: %v", err)
	}
	return &user, nil
}

// AddUser 添加新用户（可用于初始化管理员账号）
func (c *Client) AddUser(username, password string) error {
	query := "INSERT INTO user (username, password) VALUES (?, ?)"
	_, err := c.Exec(query, username, password)
	return err
}
